program_name := textator
texts_dir := text
source_dirs := src src/analyze src/io src/parse src/output src/synthesize
include_dirs := include $(texts_dir)

output_dir := bin
install_dir := ~/bin

text_files := $(wildcard $(addsuffix /*.txt,$(texts_dir)))
cpp_texts := $(text_files:.txt=.cpp)
h_texts := $(text_files:.txt=.h)

source_files := $(wildcard $(addsuffix /*.cpp,$(source_dirs))) $(cpp_texts)
object_files := $(notdir $(source_files))
object_files := $(addprefix $(output_dir)/,$(object_files:.cpp=.o))

CXX_FLAGS := -DNDEBUG -O3 -g -Wall -Wextra -ansi -pedantic -pedantic-errors\
            -ffunction-sections -fdata-sections -funsigned-char\
            $(addprefix -I, $(include_dirs)) -pipe

LD_FLAGS := -s -pipe

TEXTATOR_FLAGS := --process --cpp --symboltype "String::value_type" --memtype "extern const" --tab 2 --width 112

all: $(output_dir) $(h_texts) $(cpp_texts) $(program_name)

$(output_dir):
	mkdir $(output_dir)

$(program_name): $(object_files)
	g++ $(LD_FLAGS) $^ -o $@

VPATH := $(source_dirs) $(texts_dir)

$(texts_dir)/%.cpp: %.txt
	$(install_dir)/$(program_name) $(TEXTATOR_FLAGS) --inline --output $@ $^

$(texts_dir)/%.h: %.txt
	$(install_dir)/$(program_name) $(TEXTATOR_FLAGS) --noinline --output $@ $^

$(output_dir)/%.o: %.cpp
	g++ $(CXX_FLAGS) -c -MD $< -o $@

clean:
	rm -f $(output_dir)/*.d
	rm -f $(output_dir)/*.o
	rm -f $(program_name)

install:
	cp $(program_name) $(install_dir)

include $(wildcard *.d)
